package com.newthread.android.ui.bbs;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.jpush.im.android.eventbus.EventBus;
import com.actionbarsherlock.app.SherlockFragment;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.newthread.android.R;
import com.newthread.android.adapter.BbsHotAdapter;
import com.newthread.android.bean.bbs.BbsHotItem;
import com.newthread.android.bean.remoteBean.bbs.Post;
import com.newthread.android.bean.remoteBean.bbs.PostImage_1;
import com.newthread.android.manager.BmobRemoteDateManger;
import com.newthread.android.util.Loger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by jindongping on 15/6/4.
 */
public class BbsHotFrament extends SherlockFragment {
    public enum STATES {发帖, 我的收藏, 我的回复, 过滤}

    private ListView listView;
    private Context context;
    private List<BbsHotItem> datas = new ArrayList<>();
    private BbsHotAdapter adapter;
    private int page = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        context = getSherlockActivity();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(STATES message) {
        if (message.equals(STATES.发帖)) {
            Intent intent = new Intent(context, BbsWritePostActivity.class);
            startActivity(intent);
        }
        if (message.equals(STATES.我的收藏)) {
            Toast.makeText(context, "该功能正在制作中,please wating....", Toast.LENGTH_LONG).show();
        }
        if (message.equals(STATES.我的回复)) {
            Toast.makeText(context, "该功能正在制作中,please wating....", Toast.LENGTH_LONG).show();
        }
        if (message.equals(STATES.过滤)) {
            Toast.makeText(context, "该功能正在制作中,please wating....", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View viewRoot = inflater.inflate(R.layout.fragment_bbs_hot, container, false);
        page = 0;
        initView(viewRoot);
        if (datas != null) {
            datas.clear();
            initData(null, null, 0);
        } else {
            datas = new ArrayList<>();
            initData(null, null, 0);
        }
        return viewRoot;
    }


    private void initView(View viewRoot) {
        PullToRefreshListView refreshListView = (PullToRefreshListView) viewRoot.findViewById(R.id.refreshListView);
        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                initData(refreshView, PullToRefreshBase.Mode.PULL_FROM_START, 0);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                initData(refreshView, PullToRefreshBase.Mode.PULL_FROM_END, page);
            }
        });
        listView = refreshListView.getRefreshableView();
        adapter = new BbsHotAdapter(context, datas);
        listView.setAdapter(adapter);
        listView.setSelector(R.drawable.list_item_selector);
    }

    int finshCount;
    int currentPostSize;

    private void initData(final PullToRefreshBase<ListView> refreshView, final PullToRefreshBase.Mode mode, int page) {
        BmobQuery<Post> queryPost = new BmobQuery<>();
        //按时间排序
        queryPost.order("-createdAt");
        //包含作者和种类
        queryPost.include("author,type");
        queryPost.setLimit(10);
        queryPost.setSkip(page * 10);
        queryPost.findObjects(context, new FindListener<Post>() {
            @Override
            //一次查询 10个post 但是数据加载完后不是10个 currentPostSize为0时表示下拉刷新没有了
            public void onSuccess(final List<Post> posts) {
                currentPostSize = posts.size();
                if (currentPostSize == 0) {
                    if (refreshView != null)
                        refreshView.onRefreshComplete();
                    Toast.makeText(context, "已经没有数据了哦", Toast.LENGTH_LONG).show();
                }
                for (final Post post : posts) {
                    //查询每个post 的Image
                    PostImage_1 image = new PostImage_1();
                    image.setPost(post);
                    BmobRemoteDateManger.getInstance(context).querry(image, new FindListener<PostImage_1>() {
                        //会回调  10 次,里面代码需要每次都执行
                        @Override
                        public void onSuccess(List<PostImage_1> list) {
                            if (mode == null) {
                                //TODO 查询评论
                                BbsHotItem item = new BbsHotItem(post, list);
                                datas.add(item);
                                return;
                            }
                            if (mode == PullToRefreshBase.Mode.PULL_FROM_START) {
                                BbsHotItem item = new BbsHotItem(post, list);
                                if (!datas.contains(item)) {
                                    //TODO 查询评论
                                    datas.add(0, item);
                                }
                            } else if (mode == PullToRefreshBase.Mode.PULL_FROM_END) {
                                //TODO 查询评论
                                BbsHotItem item = new BbsHotItem(post, list);
                                datas.add(item);
                            }
                        }

                        //会回调10次 但是里面的代码只能执行一次    但是数据加载完后不是10个
                        @Override
                        public void onFinish() {
                            super.onFinish();
                            if (currentPostSize == 10) {
                                finshCount++;
                                if (finshCount == 10) {
                                    finshCount = 0;
                                    sortAndMode(refreshView, mode);
                                }
                            } else {
                                sortAndMode(refreshView, mode);
                                Toast.makeText(context, "已经没有数据了哦", Toast.LENGTH_LONG).show();
                            }
                        }

                        @Override
                        public void onError(int i, String s) {
                            if (refreshView != null) {
                                refreshView.onRefreshComplete();
                            }
                            Loger.V("查询失败" + i + s);
                            Toast.makeText(context, "查询失败,请检查网络", Toast.LENGTH_LONG).show();
                        }
                    });

                }
            }

            @Override
            public void onError(int i, String s) {
                if (refreshView != null) {
                    refreshView.onRefreshComplete();
                }
                Loger.V("查询失败" + i + s);
                Toast.makeText(context, "查询失败,请检查网络 ", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void sortAndMode(PullToRefreshBase<ListView> refreshView, PullToRefreshBase.Mode mode) {
        Collections.sort(datas, new Comparator<BbsHotItem>() {
            @Override
            public int compare(BbsHotItem lhs, BbsHotItem rhs) {
                return rhs.getPost().getCreatedAt().compareTo(lhs.getPost().getCreatedAt());
            }
        });
        adapter = new BbsHotAdapter(context, datas);
        //initView时 refreshView为空
        if (refreshView == null) {
            listView.setAdapter(adapter);
        } else if (mode == PullToRefreshBase.Mode.PULL_FROM_START) {
            listView.setAdapter(adapter);
            refreshView.onRefreshComplete();
        } else if (mode == PullToRefreshBase.Mode.PULL_FROM_END) {
            adapter.notifyDataSetChanged();
            refreshView.onRefreshComplete();
        }
    }

}
